#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "../entity.h"
#include "../file.h"
#include "../dir.h"

#include "../cmd.h"

#include <ncurses.h>
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <vector>
#include <string>

using namespace std;

enum Mode {
    m_std, m_search, m_cmd, m_completion
};

class MainWindow {
public:
   
	vector<Entity*> visibleItems = {};
    vector<Entity*> currentItems = {};
	vector<Entity*> menuItems    = {};

    vector<string> history = {};
    int historyIndex = 0;

    CMD cmd = CMD();

    string cmdLine      = "";
    string searchQuery  = "";

    Mode curMode = m_std;

    bool showHidden     = false;
	
    wchar_t currentItem = 0;
	int lastItem        = 0;

    string currentDirPath = "";
	string statusText = " ";
	
    WINDOW *win         = nullptr;
	bool terminated     = false;
	
    int screen          = 0;
	int lastKey         = 0;
	int indent          = 3;
	int scrollTop       = 0;
	int maxRows         = 0;
	int maxX            = 0;
	int maxY            = 0;

	MainWindow(vector<Entity*> &items);
	static Entity* pickItem(Dir* dir) {
        vector<Entity*> items = dir->getItems();
        MainWindow window = MainWindow(items);
        window.initWindow();
        window.currentDirPath = dir->path;
        return window.start();
    }   

    void moveUp();
	void moveDown();

    void updateScrollTop();

    Entity* cmdKeys();
    Entity* searchKeys();
    Entity* defaultKeys();

    void initTerm();
    void initColors();
    void initWindow();
    void inputKey();
    Entity* process();
    Entity* start();

    void drawHeader();
    void drawSearchedItem(int startY, int startX, string &name);
    void drawBody();
	void drawStatus();
    void drawSearch();
    void drawCmd();
    void drawPreview();
    void drawDirPreview(Dir* dir);
    void drawFilePreview(File* file);
	void drawMainScreen();

    void saveCommandToHistory();
    void loadHistory();

    void moveHistoryUp() {
        historyIndex--;
        if (historyIndex < 0) historyIndex = 0;
        if (history.size() > 0)
            cmdLine = history[historyIndex];
        else
            cmdLine = "";
    }

    void moveHistoryDown() {
        historyIndex++;
        int size = history.size();
        if (historyIndex > size) historyIndex = size;
        if (historyIndex < size) 
            cmdLine = history[historyIndex];
        else
            cmdLine = "";
    }

    void completion();
    
    void toggleSearchMode();
    void turnStdMode();
    void toggleCmdMode();

	vector<Entity*> getVisibleItems();
	void clearLine(int y, int l);
};

#endif // MAINWINDOW_H




